const api = require('../../../../ws_micro_shop/utils/api.js');
const utils = require('../../../../ws_micro_shop/utils/utils.js');
const tools = require('../../../../ws_micro_shop/utils/getuserinfo.js');
let _timer = null;
let countdown = null;

const app = getApp();
const { module: moduleName } = app.siteInfo;
const util = app.util;

let p = 1;

Page({
  data: {
    show_attr_picker: false,
    form: {
      number: 1,
    },
    idx: 1,
    level: 0,
    comment_list: [],
    comment_count: {
      score_all: 0,
      score_6: 0,
      score_3: 0,
      score_2: 0,
      score_1: 0,
    },
    img_hide: true,
    hide: 'hide',
    url: '',
    autoplay: true,
    attachment_url: app.siteInfo.attachment_url,
    theme: app.themeData,
    abnorData: {
      imgSrc: '/common/static/images/abnor-09.png',
      text: '暂无相关评价',
    },
    show_service: false,
    unit: '',
    show_rule: false,
    imgUrl: app.imgUrl,
    isLoad: false,
    clickAttr: false,
  },
  onLoad(op) {
    let options = op || {};
    app.v8_card_action_log = [];
    let parent_id = 0;
    let shop_id = 0;
    let share_scene = '';
    let user_id = options.user_id;
    let scene = decodeURIComponent(options.scene);
    app.tabbarindex = options.tabbarindex ? options.tabbarindex - 0 : app.tabbarindex;
    app.pageOnLoad(this);
    app.bindGuide(op);
    let userinfo = wx.getStorageSync('user_info');
    let store = wx.getStorageSync('store');
    let that = this;
    if (options && options.shopid) {
      app.ws_micro_shop_globalData.shopid = options.shopid;
      shop_id = options.shopid;
    }
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    if (user_id) {
      parent_id = user_id;
      share_scene = 4;
    } else if (scene) {
      let { uid, gid, sid, g_id } = utils.scene_decode(scene);
      if (g_id && gid) {
        app.ws_micro_shop_globalData.last_share_guide_id = g_id;
        app.ws_micro_shop_globalData.last_share_good_id = gid;
        app.ws_micro_shop_globalData.shopid = sid;
        options.gid = gid;
        options.guide_id = g_id;
        options.shopid = sid;
        shop_id = sid;
      }
      if (uid && gid) {
        parent_id = uid;
        options.gid = gid;
        shop_id = sid;
        app.ws_micro_shop_globalData.shopid = sid;
      } else {
        parent_id = scene;
      }
      share_scene = 6;
    }
    parent_id && (app.ws_micro_shop_globalData.parent_id = parent_id);
    app.loadShopSetting().then(res => {
      that.setData(res);
    }).then(() => {
      that.getFloatIcon();
    });
    let sessionFormStr = {
      shop_id: app.ws_micro_shop_globalData.shopid,
    };
    let serviceMessageTitle = '';
    let serviceMessagePath = 'details?gid=' + options.gid;

    if (userinfo && store) {
      Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
      Number(store.comment_switch) === 1 && this.getComments(options.gid, 0, 1);
      app.loginBindParent({
        parent_id,
        shop_id,
        share_scene,
      });
      this.setData({
        store,
      });
      util.prepareBindInfo(options, moduleName, that);
      this.bindCard(options); 
    } else {
      app.ws_micro_shoplogin().then(res => {
        userinfo = wx.getStorageSync('user_info');
        Number(userinfo.info) === 0 && tools.onGetInfo(that, userinfo.auth_mode);
        util.prepareBindInfo(options, moduleName, that);
        this.bindCard(options); 
        app.getStoreData().then(res => {
          store = wx.getStorageSync('store');
          Number(store.comment_switch) === 1 && that.getComments(options.gid, 0, 1);
          app.loginBindParent({
            parent_id,
            shop_id,
            share_scene,
          });
          that.setData({
            store,
          });
        });
      });
    }
    if (options.guide_id) {
      app.ws_micro_shop_globalData.last_share_guide_id = options.guide_id;
      app.ws_micro_shop_globalData.last_share_good_id = options.gid;
    }
    this.setData({
      opts: options,
      parent_id,
      shop_id,
      share_scene,
      sessionFormStr: JSON.stringify(sessionFormStr),
      serviceMessagePath,
      serviceMessageTitle,
      id: options.gid,
      isSaas: app.ws_micro_shop_globalData.isSaas,
      orgPrice: store.show_original_price && store.show_original_price == 1 ? 1 : 0
    });
  },
  onShow() {
    wx.setNavigationBarTitle({
      title: '拼团详情',
    });
    this.setData({
      isLoad: false,
      clickAttr: false,
    })
    this.getGoodsInfo();
  },
  onShareAppMessage() {
    let that = this;
    let goods = that.data.goods;
    let user_info = wx.getStorageSync('user_info');
    let path = '/ws_micro_shop_pt/pages/pt/details/details?gid=' + goods.id + '&user_id=' + user_info.id + '&tabbarindex=' + app.tabbarindex + '&shopid=' + app.ws_micro_shop_globalData.shopid;
    path = util.spliceSharePath(path, '4', moduleName);
    let shareShowPrice = wx.getStorageSync('store') && wx.getStorageSync('store').share_show_price;
    return {
      title: `${Number(shareShowPrice) === 1 ? that.data.goods.price + '元' : ''}${that.data.goods.name}`,      
      path,
      imageUrl: goods.cover_pic,
    };
  },
  onShareTimeline() {
    let that = this;
    let goods = that.data.goods;
    let user_info = wx.getStorageSync('user_info');
    let shareShowPrice = wx.getStorageSync('store') && wx.getStorageSync('store').share_show_price;
    return {
      title: `${Number(shareShowPrice) === 1 ? that.data.goods.price + '元' : ''}${that.data.goods.name}`,
      imageUrl: goods.cover_pic,
      query: 'gid=' + goods.id + '&user_id=' + user_info.id + '&tabbarindex=' + app.tabbarindex + '&shopid=' + app.ws_micro_shop_globalData.shopid
    }
  },
  onHide() {
    util.sendBindInfo(this.data);
    countdown && clearInterval(countdown);
    _timer && clearInterval(_timer);
  },
  onUnload() {
    util.sendBindInfo(this.data);
    countdown && clearInterval(countdown);
    _timer && clearInterval(_timer);
  },
  bindCard(options) {
    app.bindCard(options.openid, options.share_scene);
    app.v8_card_action_log.push({ name: 'transmitGoods', data:{goodsID: options.gid, type: 'pt'}, timestamp: new Date().getTime(), to_openid: options.openid });
    app.util.statRequest({
      aa: JSON.stringify(app.v8_card_action_log),
      is_module: 0
    });
  },
  getGoodsInfo() {
    let _this = this;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    wx.showNavigationBarLoading();
    app.ws_micro_shoprequest({
      url: api.group.details,
      method: 'GET',
      data: {
        gid: _this.data.id,
      },
      success: function (res) {
        if (res.code === 0) {
          if (res.data.info.limit_time_ms && res.data.info.limit_time_ms.length > 0) {
            _this.countDownRun(_this.computeTime(res.data.info.limit_time_ms));
          }
          // wx.setNavigationBarTitle({
          //   title: res.data.info.name,
          // });
          wx.hideNavigationBarLoading();
          let reduce_price = (res.data.info.original_price - res.data.info.price).toFixed(2);
          // 处理姓名 ***
          let group_list = res.data.groupList;
          for (let i = 0; i < group_list.length; i++) {
            if (group_list[i].nickname.length > 1) {
              group_list[i].nickname = group_list[i].nickname.substr(0, 1) + '***' + group_list[i].nickname.substr(group_list[i].nickname.length - 1, 1);
            } else {
              group_list[i].nickname = group_list[i].nickname.substr(0, 1) + '***';
            }
          }
          _this.setData({
            goods: res.data.info,
            attr_group_list: res.data.attr_group_list,
            limit_time: res.data.limit_time || '',
            group_list,
            group_num: res.data.groupList.length,
            group_rule_id: res.data.groupRuleId,
            reduce_price: reduce_price < 0 ? 0 : reduce_price,
            serviceMessageTitle: res.data.info.name,
            show_goods_comment: res.data.show_goods_comment,
          });
          _this.countDown();
          _this.selectDefaultAttr();
        } else if (res.code === -3) {
          app.ws_micro_shoplogin().then(res => {
            let userinfo = wx.getStorageSync('user_info');
            Number(userinfo.info) === 0 && tools.onGetInfo(_this, userinfo.auth_mode);
            util.prepareBindInfo(_this.data.opts, moduleName, _this);
            app.getStoreData().then(res => {
              let store = wx.getStorageSync('store');
              Number(store.comment_switch) === 1 && _this.getComments(_this.data.opts.id, 0, 1);
              _this.setData({
                store,
              });
              app.loginBindParent({
                parent_id: _this.data.parent_id,
                shop_id: _this.data.shop_id,
                share_scene: _this.data.share_scene,
              });
            });
            _this.getGoodsInfo(_this.data.opts);
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                app.util.navigateTo('/ws_micro_shop_pt/pages/pt/index/index', {}, true);
              }
            },
          });
        }
      },
      complete: res => {
        setTimeout(() => {
          wx.hideLoading();
        }, 1000);
      },
    });
  },
  selectDefaultAttr() {
    let { attr_group_list, goods } = this.data;
    if (!goods || goods.use_attr !== '0') {
      return;
    }
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        for (let j in attr_group_list[i].attr_list) {
          if (Number(i) === 0 && Number(j) === 0) {
            attr_group_list[i].attr_list[j]['checked'] = true;
          }
        }
      }
    }
    this.setData({
      attr_group_list,
    });
  },
  computeTime(limit_time_ms) {
    let endTime = new Date(limit_time_ms[0], limit_time_ms[1] - 1, limit_time_ms[2], limit_time_ms[3], limit_time_ms[4], limit_time_ms[5]);
    return endTime;
  },
  countDownRun(endTime) {
    _timer && clearInterval(_timer);
    let that = this;
    let leftTime = endTime - (new Date());
    let timeout = leftTime % 1000 || 0;
    _timer = setTimeout(() => {
      that.countDownRun(endTime);
    }, timeout);
    that.saveTime(leftTime);
  },
  saveTime(leftTime) {
    let days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10);
    let hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10);
    let minutes = parseInt(leftTime / 1000 / 60 % 60, 10);
    let seconds = parseInt(leftTime / 1000 % 60, 10);
    days = this.checkTime(days);
    hours = this.checkTime(hours);
    minutes = this.checkTime(minutes);
    seconds = this.checkTime(seconds);
    if (leftTime <= 0) {
      _timer && clearInterval(_timer);
    }
    this.setData({
      limit_time: {
        days: days < 0 ? '00' : days,
        hours: hours < 0 ? '00' : hours,
        mins: minutes < 0 ? '00' : minutes,
        secs: seconds < 0 ? '00' : seconds,
      },
    });
  },
  checkTime(num) {
    let i = num;
    if (i < 0) {
      return '00';
    }
    if (i < 10) {
      i = '0' + i;
    }
    return i;
  },
  getComments(id, score, page) {
    let _this = this;
    app.ws_micro_shoprequest({
      url: api.group.comment,
      method: 'GET',
      data: {
        gid: id,
        score,
        page,
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.comment.length > 0) {
          _this.setData({
            comment_count: res.data.comment_count,
            comment_list: _this.data.comment_list.concat(res.data.comment.splice(0, 1)),
            good_per: res.data.good_per,
          });
        }
      },
    });
  },
  commentPicView(e) {
    let _this = this;
    let index = e.currentTarget.dataset.index;
    let pic_index = e.currentTarget.dataset.pic_index;
    wx.previewImage({
      current: _this.data.comment_list[index].pic_list[pic_index],
      urls: _this.data.comment_list[index].pic_list,
    });
  },
  onReachBottom() {
  },
  goHome() {
    app.util.navigateTo('/ws_micro_shop_pt/pages/pt/index/index', {}, true);
  },
  goToGroup(e) {
    wx.navigateTo({
      url: '/ws_micro_shop_pt/pages/pt/group/details?oid=' + e.currentTarget.dataset.id,
    });
  },
  goArticle(e) {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.article_detail,
      data: {
        id: that.data.group_rule_id,
      },
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            content: res.data.content,
            show_rule: true,
      });
    }
      },
    });

  },
  closeRule() {
    this.setData({
      show_rule: false,
    })
  },
  hideAttrPicker() {
    this.setData({
      show_attr_picker: false,
    });
  },
  disabledClick() {
    // it`s necessary
  },
  showAttrPicker() {
    this.setData({
      show_attr_picker: true,
    });
  },
  attrClick: function (e) {
    let that = this;
    let attr_group_id = Number(e.currentTarget.dataset.groupId);
    let attr_id = Number(e.currentTarget.dataset.id);
    let attr_group_list = that.data.attr_group_list;
    for (let i in attr_group_list) {
      if (Number(attr_group_list[i].attr_group_id) !== attr_group_id) {
        continue;
      }
      for (let j in attr_group_list[i].attr_list) {
        if (Number(attr_group_list[i].attr_list[j].attr_id) === attr_id) {
          attr_group_list[i].attr_list[j].checked = true;
          attr_group_list[i].attr_name = attr_group_list[i].attr_list[j].attr_name;
        } else {
          attr_group_list[i].attr_list[j].checked = false;
        }
      }
    }
    that.setData({
      attr_group_list: attr_group_list,
      clickAttr: true,
    });
    let check_attr_list = [];
    let check_all = true;
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        let group_checked = false;
        for (let j in attr_group_list[i].attr_list) {
          if (attr_group_list[i].attr_list[j].checked) {
            check_attr_list.push(attr_group_list[i].attr_list[j].attr_id);
            group_checked = true;
            break;
          }
        }
        if (!group_checked) {
          check_all = false;
          break;
        }
      }
    }
    if (!check_all) {
      return;
    }
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.group.goods_attr_info,
      data: {
        goods_id: that.data.goods.id,
        attr_list: JSON.stringify(check_attr_list),
      },
      success: function (res) {
        wx.hideLoading();
        if (res.code === 0) {
          let goods = that.data.goods;
          goods.price = res.data.price;
          goods.num = res.data.num;
          goods.attr_pic = res.data.pic;
          goods.original_price = res.data.single;
          that.setData({
            goods: goods,
          });
        }
      },
    });
  },
  buyNow() {
    this.submit('GROUP_BUY');
  },
  onlyBuy() {
    this.submit('ONLY_BUY');
  },
  submit(type) {
    let that = this;
    that.setData({
      type: type,
    });
    if (!that.data.show_attr_picker) {
      that.setData({
        show_attr_picker: true,
      });
      return true;
    }
    if (that.data.goods && that.data.form.number > that.data.goods.num) {
      wx.showToast({
        title: '商品库存不足，请选择其它规格或数量',
        icon: 'none',
      });
      return true;
    }
    let attr_group_list = that.data.attr_group_list;
    let checked_attr_list = [];
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        let attr = false;
        for (let j in attr_group_list[i].attr_list) {
          if (attr_group_list[i].attr_list[j].checked) {
            attr = {
              attr_id: attr_group_list[i].attr_list[j].attr_id,
              attr_name: attr_group_list[i].attr_list[j].attr_name,
            };
            break;
          }
        }
        if (!attr) {
          wx.showToast({
            title: '请选择' + attr_group_list[i].attr_group_name,
            icon: 'none',
          });
          return true;
        } else {
          checked_attr_list.push({
            attr_group_id: attr_group_list[i].attr_group_id,
            attr_group_name: attr_group_list[i].attr_group_name,
            attr_id: attr.attr_id,
            attr_name: attr.attr_name,
          });
        }
      }
    }
    that.setData({
      show_attr_picker: false,
    });
    wx.navigateTo({
      url: '/ws_micro_shop_pt/pages/pt/order-submit/order-submit?goods_info=' + JSON.stringify({
        goods_id: that.data.goods.id,
        attr: checked_attr_list,
        num: that.data.form.number,
        type: type,
        deliver_type: that.data.goods.type,
      }),
    });
  },
  numberSub() {
    let num = this.data.form.number;
    if (num <= 1) {
      return true;
    }
    num--;
    this.setData({
      form: {
        number: num,
      },
    });
  },
  numberAdd() {
    let num = this.data.form.number;
    num++;
    if (this.data.goods && num > this.data.goods.one_buy_limit && Number(this.data.goods.one_buy_limit) !== 0) {
      wx.showModal({
        title: '提示',
        content: '数量超过最大限购数',
        showCancel: false,
      });
      return;
    }
    this.setData({
      form: {
        number: num,
      },
    });
  },
  numberBlur(e) {
    let num = e.detail.value;
    num = parseInt(num, 10);
    if (isNaN(num)) {
      num = 1;
    }
    if (num <= 0) {
      num = 1;
    }
    if (num > this.data.goods.one_buy_limit && Number(this.data.goods.one_buy_limit) !== 0) {
      wx.showModal({
        title: '提示',
        content: '数量超过最大限购数',
        showCancel: false,
      });
      num = this.data.goods.one_buy_limit;
    }
    this.setData({
      form: {
        number: num,
      },
    });
  },
  countDown() {
    let that = this;
    countdown = setInterval(function () {
      let group_list = that.data.group_list;
      for (let i in group_list) {
        if (Object.prototype.hasOwnProperty.call(group_list, i)) {
          let leftTime = (new Date(group_list[i]['limit_time_ms'][0], group_list[i]['limit_time_ms'][1] - 1, group_list[i]['limit_time_ms'][2], group_list[i]['limit_time_ms'][3], group_list[i]['limit_time_ms'][4], group_list[i]['limit_time_ms'][5])) - (new Date());
          let days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10);
          let hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10);
          let minutes = parseInt(leftTime / 1000 / 60 % 60, 10);
          let seconds = parseInt(leftTime / 1000 % 60, 10);
          days = that.checkTime(days);
          hours = that.checkTime(hours);
          minutes = that.checkTime(minutes);
          seconds = that.checkTime(seconds);
          group_list[i].limit_time = {
            days: days,
            hours: hours > 0 ? hours : '00',
            mins: minutes > 0 ? minutes : '00',
            secs: seconds > 0 ? seconds : '00',
          };
          that.setData({
            group_list: group_list,
            isLoad: true,
          });
        }
      }
    }, 1000);
  },
  bigToImage(e) {
    let urls = this.data.comment[e.currentTarget.dataset.index]['pic_list'];
    wx.previewImage({
      current: e.currentTarget.dataset.url,
      urls: urls,
    });
  },
  onGoodsImageClick(e) {
    let urls = [];
    let index = e.currentTarget.dataset.index;
    for (let i in this.data.goods.pic_list) {
      if ({}.hasOwnProperty.call(this.data.goods.pic_list, i)) {
        urls.push(this.data.goods.pic_list[i]);
      }
    }
    wx.previewImage({
      urls: urls,
      current: urls[index],
    });
  },
  showShareModal() {
    this.setData({
      share_modal_active: 'active',
      no_scroll: true,
    });
  },
  shareModalClose() {
    this.setData({
      share_modal_active: '',
      no_scroll: false,
    });
  },
  getGoodsQrcode() {
    let that = this;
    that.setData({
      goods_qrcode_active: 'active',
      share_modal_active: '',
    });
    if (that.data.goods_qrcode) {
      return true;
    }
    app.ws_micro_shoprequest({
      url: api.group.goods_qrcode,
      data: {
        goods_id: that.data.id,
      },
      success: function (res) {
        if (res.code === 0) {
          that.setData({
            goods_qrcode: res.data.pic_url,
          });
        }
        if (res.code === 1) {
          that.goodsQrcodeClose();
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
  },
  goodsQrcodeClose() {
    this.setData({
      goods_qrcode_active: '',
      no_scroll: false,
    });
  },
  saveGoodsQrcode() {
    let that = this;
    if (!wx.saveImageToPhotosAlbum) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
      return;
    }
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.writePhotosAlbum'] === 'undefined') {
          that.downLoadGoodsImg();
        } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
          that.setData({
            open_setting: true,
          });
        } else {
          that.downLoadGoodsImg();
        }
      },
    });
  },
  downLoadGoodsImg() {
    let _this = this;
    wx.showLoading({
      title: '正在下载图片',
      mask: true,
    });
    wx.downloadFile({
      url: _this.data.goods_qrcode,
      success: function (e) {
        wx.showLoading({
          title: '正在保存图片',
          mask: true,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function () {
            wx.showModal({
              title: '提示',
              content: '商品海报保存成功',
              showCancel: false,
            });
          },
          fail: function (e) {
            wx.showModal({
              title: '提示',
              content: '图片保存失败',
              showCancel: false,
            });
          },
          complete: function (e) {
            wx.hideLoading();
          },
        });
      },
      fail: function (e) {
        wx.showModal({
          title: '图片下载失败',
          content: e.errMsg + ';' + _this.data.goods_qrcode,
          showCancel: false,
        });
      },
      complete: function (e) {
        wx.hideLoading();
      },
    });
  },
  goodsQrcodeClick(e) {
    let src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },
  play(e) {
    let url = e.currentTarget.dataset.url;
    this.setData({
      url: url,
      hide: '',
      autoplay: false,
    });
    let videoContext = wx.createVideoContext('video');
    videoContext.play();
  },
  close(e) {
    if (e.currentTarget.id === 'video') {
      return true;
    }
    this.setData({
      hide: 'hide',
      autoplay: true,
    });
    let videoContext = wx.createVideoContext('video');
    videoContext.pause();
  },
  hide(e) {
    if (Number(e.detail.current) === 0) {
      this.setData({
        img_hide: true,
      });
    } else {
      this.setData({
        img_hide: false,
      });
    }
  },
  to_dial() {
    let contact_tel = this.data.contact_tel;
    wx.makePhoneCall({
      phoneNumber: contact_tel,
    });
  },
  openService() {
    this.setData({
      show_service: true,
    });
  },
  closeService() {
    this.setData({
      show_service: false,
    });
  },
  downloadPicture() {
    utils.downLoad(this);
  },
  wxmlTagATap(e) {
    let src = e.detail.src || false;
    let reUrl = /^\//;
    if (!src) {
      return;
    } else {
      if (reUrl.test(src)) {
        app.util.navigateTo('/ws_micro_shop' + src);
      } else {
        app.util.navigateTo('/ws_micro_shop/pages/web/web?url=' + src);
      }
    }
  },
  collectFormId(e) {
    app.collectFormId(e);
  },
  tabMiniCard(e) {
    let args = e.detail;
    let currentPath = '';
    let pages = getCurrentPages();
    pages.length > 0 && (currentPath = '/' + pages.pop().route);
    (currentPath !== args.path
      || String(this.data.opts.gid) !== args.query.id)
      && setTimeout(() => {
        app.util.navigateTo(args.path, args.query);
      }, 500);
  },
  customerTo() {
    let { card_openid, card_toopenid, card_id } = this.data;
    let url = '/common/component/universal-card/pages/message?openid=' + card_openid + '&to_openid=' + card_toopenid + '&cardid=' + card_id + '&scene=inner&m_id=0';
    app.util.navigateTo(url);
  },
  getFloatIcon() {
    let that = this;
    let { dial, dial_pic, contact_tel, web_service, web_service_url, show_customer_service, serviceMessageTitle, serviceMessagePath, service, show_qywxcustomer_service, show_qywxcustomer_pic, card_openid, card_toopenid, card_id } = that.data;
    let floatItems = [
      {
        type: 1, // 客服电话
        show: dial == 1,
        icon: dial_pic,
        tel: contact_tel,
      },
      {
        type: 6, // 企业客服
        show: show_qywxcustomer_service == 1,
        icon: show_qywxcustomer_pic,
      },
      {
        type: 3, // webview跳转
        show: web_service,
        icon: web_service,
        url: web_service_url,
      },
      {
        type: 0, // 推荐
        show: false,
        iconClass: 'icon icon-xin',
        event: 'recommend',
      }
    ]
    
    let customerlist;
    if (Number(show_customer_service) === 1) {
      customerlist = [
        {
          type: 4, // 客服跳转
          show: true,
          icon: service,
          sessionFormStr: JSON.stringify({
            shop_id: app.ws_micro_shop_globalData.shopid,
          }),
          serviceMessageTitle: serviceMessageTitle,
          serviceMessagePath: serviceMessagePath,
        }
      ]
    } else if (Number(show_customer_service) === 2 || Number(show_customer_service) === 3) {
      customerlist = [
        {
          type: 7, //内部跳转
          show: true,
          icon: service,
          url: '/common/component/universal-card/pages/message?openid=' + card_openid + '&to_openid=' + card_toopenid + '&cardid=' + card_id + '&scene=inner&m_id=0'
        },
      ]
    }
    customerlist && (floatItems = floatItems.concat(customerlist));
    that.setData({
      floatItems
    },() => {
      that.checkUserCardManage();
    });
  },

  // 判断当前模块是否开启了推荐
  checkRecommandBtn(){
    let { floatItems } = this.data;
    app.util.request({
      url:'card/record/getModuleRecommandButton',
      success: res => {
        let {errcode, data} = res.data;
        if(errcode == 0){
          floatItems.forEach(item =>{
            if(item.event == 'recommend'){
              item.show = data == 1? true: false;
            }
          })
          this.setData({
            floatItems
          })
        }
      }
    })
  },

  // 判断当前用户是否有名片及商品是否被加入到名片推荐商品中
  checkUserCardManage(){
    let { gid } = this.options;
    let { floatItems } = this.data;
    app.util.request({
      url:'card/record/getUserCardManage',
      data:{
        id:gid,
        type:'2',
        openid: wx.getStorageSync('openid') || wx.getStorageSync('OPENID')
      },
      success: res => {
        let {errcode, data:{is_cardmanage,is_havegoods}} = res.data;
        console.log("=====checkUserCardManage====",res.data);
        this.checkRecommandBtn();
        if(errcode == 0){
          floatItems.forEach(item =>{
            if(item.event == 'recommend'){
              item.show = is_cardmanage == 1? true: false;
              item.iconClass = is_havegoods == 1? 'icon icon-xinxin' :'icon icon-xin';
            }
          })
          this.setData({
            floatItems,
            is_havegoods
          })
        }
      }
    })
  },
  

  // 添加推荐商品
  recommend(){
    let { gid } = this.options;
    let { floatItems, is_havegoods } = this.data;
    console.log("===is_havegoods====",is_havegoods)
    app.util.request({
      url:'card/record/addCardManageGoods',
      data:{
        id: gid,
        type:'2',
        openid: wx.getStorageSync('openid') || wx.getStorageSync('OPENID'),
        options: is_havegoods == 0? '1': '2'
      },
      success: res => {
        console.log("===addCardManageGoods====",res.data.data)
        if(res.data.errcode == 0){
          is_havegoods = !is_havegoods;
          floatItems.forEach(item =>{
            if(item.event == 'recommend'){
              item.iconClass = is_havegoods == 1? 'icon icon-xinxin' :'icon icon-xin';
            }
          })
          let title = is_havegoods == 1?'推荐成功':'取消推荐成功';
          wx.showToast({
            title,
            icon:'none'
          })
        } else {
          wx.showToast({
            title:res.data.errmsg,
            icon:'none'
          })
        }
        this.setData({
          floatItems,
          is_havegoods
        })
      }
    })
  },
});
